#！/bin/bash
initOpenResty(){
echo "-----initOpenResty初始化开始执行-----"
#1）安装openresty  resty -V
find_resty=`find /opt -name openresty-1.19.3.2`
if [ $find_resty ]; then
  echo "already exists $find_resty, do nothing"
else
  echo "start deploy openresty-1.19.3.2" 
  mkdir /opt/soft
  cd /opt/soft
  wget https://openresty.org/download/openresty-1.19.3.2.tar.gz
  tar xzvf openresty-1.19.3.2.tar.gz 
  cd openresty-1.19.3.2/ 
  ./configure 
  make
  make install
fi

#2）使用root用户，创建conf.d文件夹
use_root=`grep '^user root;$' /usr/local/openresty/nginx/conf/nginx.conf`
if [ -z "$use_root" ]; then
  sed -i '/#user  nobody;/a\user root;' /usr/local/openresty/nginx/conf/nginx.conf
fi
include_cofd=`grep 'include /usr/local/openresty/nginx/conf/conf.d/\*.conf;' /usr/local/openresty/nginx/conf/nginx.conf`
if [ -z "$include_cofd" ]; then
  sed -i '/#gzip  on;/a\    include /usr/local/openresty/nginx/conf/conf.d/*.conf;' /usr/local/openresty/nginx/conf/nginx.conf
fi
if [ ! -d "/usr/local/openresty/nginx/conf/conf.d" ]; then  
  mkdir /usr/local/openresty/nginx/conf/conf.d
fi
#3）在conf.d中创建代理接口
cat > /usr/local/openresty/nginx/conf/conf.d/dbplatform.conf << END
server {
    listen 10010;
    server_name localhost;
    location /version {
        default_type 'text/plain';
        content_by_lua_block {
            ngx.say("{\"code\":200, \"data\": \"v1.0.0\", \"msg\":\"wget http://www.jvxb.com/agent/init/init_agent_v1.0.0.sh -N -P /opt/tool && chmod 777 /opt/tool/init_agent_v1.0.0.sh && bash /opt/tool/init_agent_v1.0.0.sh\"}")
        }
    }
    location /execute {
        default_type 'text/plain';
        content_by_lua_block {
            ngx.req.read_body()
            local headers = ngx.req.get_headers()
            if headers == nil then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, header['secret'] is neccessary!\"}")
                return
            end
            if headers["content-type"] ~= "application/x-www-form-urlencoded" then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, header['content-type'] should be application/x-www-form-urlencoded\"}")
                return
            end
            local secret = headers["secret"]
            if secret == nil then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, header['secret'] is neccessary!\"}")
                return
            end 
            if headers["secret"] ~= "dbplatform" then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, header['secret'] invalid!\"}")
                return
            end
            local args = ngx.req.get_post_args()
            if args == nil then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, param['cmd'] is neccessary!\"}")
                return
            end
            local cmd = args["cmd"]
            if cmd == nil then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, param['cmd'] is neccessary!\"}")
                return
            end
            os.execute(cmd)
            ngx.say("{\"code\":200, \"data\": \"\", \"msg\":\"ok\"}")
       }
    }
    location /execute/result {
        default_type 'text/plain';
        content_by_lua_block {
            ngx.req.read_body()
            local headers = ngx.req.get_headers()
            if headers == nil then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, header['secret'] is neccessary!\"}")
                return
            end
            if headers["content-type"] ~= "application/x-www-form-urlencoded" then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, header['content-type'] should be application/x-www-form-urlencoded\"}")
                return
            end
            local secret = headers["secret"]
            if secret == nil then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, header['secret'] is neccessary!\"}")
                return
            end
            if headers["secret"] ~= "dbplatform" then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, header['secret'] invalid!\"}")
                return
            end
            local args = ngx.req.get_post_args()
            if args == nil then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, param['cmd'] is neccessary!\"}")
                return
            end
            local cmd = args["cmd"]
            if cmd == nil then
                ngx.say("{\"code\":500, \"data\": \"\", \"msg\":\"execute error, param['cmd'] is neccessary!\"}")
                return
            end
            local rsfile = io.popen(cmd)
            local rschar = rsfile:read("*all")
            ngx.say("{\"code\":200, \"data\": \"", rschar, "\", \"msg\":\"ok\"}")
       }
    }
}
END
#4）启动openresty
echo '----------------start openresty-------------'
pid_resty="`lsof -i:10010`"
if [[ $pid_resty ]]; then
  /usr/local/openresty/nginx/sbin/nginx -s reload
else
  /usr/local/openresty/nginx/sbin/nginx
fi
#5）对外暴露10010端口（包括云服务器的端口）
firewall_10010=`firewall-cmd --zone=public --list-ports|grep 10010/tcp`
if [ -z "$firewall_10010" ]; then
  firewall-cmd --zone=public --add-port=10010/tcp --permanent
  firewall-cmd --reload
fi
echo "-----initOpenResty初始化执行完毕-----"
}

initDocker(){
echo "-----initDocker初始化开始执行-----"
docker_statu=`systemctl status docker|grep 'active (running)'`
if [ -z "$docker_statu" ]; then
  systemctl start docker
fi
find_docker=`docker --version|grep 20.10`
if [ $find_docker ]; then
  echo "already exists $find_docker, do nothing"
else
  echo "start deploy docker-ce-20.10.10" 
  yum -y install gcc gcc-c++ yum-utils   
  yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 
  yum makecache fast
  yum -y install docker-ce-20.10.10 docker-ce-cli-20.10.10 containerd.io
  systemctl start docker && systemctl enable docker
fi
echo "-----initDocker初始化执行完毕-----"
}

uninstall_docker(){
yum -y remove docker-* 
rm -rf /var/lib/docker /var/lib/dockershim /etc/docker /run/docker /usr/libexec/docker
}


initAgent(){
  initOpenResty
  initDocker
}

#联网获取本脚本方法/执行命令方法：
#wget http://http://www.jvxb.com/agent/init/init_agent_v1.0.0.sh -N -P /opt/tool && chmod 777 /opt/tool/init_agent_v1.0.0.sh && bash /opt/tool/init_agent_v1.0.0.sh
#curl localhost:10010/execute/result -H 'content-type: application/x-www-form-urlencoded' -H 'secret: dbplatform' -d 'cmd=free -m'
echo "-----机器初始化开始执行-----"
initAgent
echo "-----机器初始化执行完毕-----"